--- 通过cookie认证用户, 失败跳转 /extrauth/login.html
--- https://www.stavros.io/posts/writing-an-nginx-authentication-module-in-lua/

--这两个var是在nginx配置时设置的
local auth_group = ngx.var.extrauth_group
if auth_group == nil then
    auth_group = 'default'
end
local need_admin = ngx.var.need_admin
if need_admin == nil then
    need_admin = false
end

-- 认证用cookie名为 extrauth_{auth_group}_token
local cookie = ngx.var['cookie_extrauth_token']

local code = extrauth_cons.authenticate(cookie, need_admin, auth_group)
if code == 1 then
    local redirect_url = ndk.set_var.set_escape_uri(ngx.var.scheme .. "://" .. ngx.var.server_name .. ":" .. ngx.var.server_port)
    ngx.header["Set-Cookie"] = 'extrauth_redirect=' .. redirect_url
    ngx.redirect("http://localhost:80/extrauth/login.html")
elseif code == 2 then
    ngx.log(ngx.ERR, "Try to access restricted area: ", cookie," auth group " , auth_group)
    ngx.header.content_type = "text/plain"
    ngx.status = 403
    ngx.say("Extrauth: You do not have group auth: " .. auth_group)
    ngx.exit(403)
end